<template>
  <div class="tinymce-editor">
    <editor placeholder="请输入文本内容... " class="editor" :id="tinymceId" v-model.trim="myValue" :init="init" v-bind="$attrs" v-on="inputListeners"> </editor>
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
// 引入富文本编辑器主题的js和css
import 'tinymce/themes/silver'
export default {
  name: 'Tinymce',
  components: {
    Editor,
  },
  props: {
    id: {
      type: String,
      default: function () {
        return new Date().getTime() + ''
      },
    },
    // value: {
    //   type: String,
    //   default: '',
    // },
    height: {
      type: [Number, String],
      default: '100%',
    },
  },
  data() {
    // const that = this;
    return {
      tinymceId: this.id,
      init: {
        selector: `#${this.tinymceId}`,
        language_url: '/tinymce/langs/zh_CN.js', // 语言包的路径
        language: 'zh_CN', //语言
        skin_url: '/tinymce/skins/ui/oxide', // skin路径
        height: this.height, //编辑器高度
        branding: true, //是否禁用“Powered by TinyMCE”
        menubar: false, //顶部菜单栏显示
        statusbar: false, //是否显示底部的状态栏
        plugins: '',
        toolbar: '', // （自定义工具栏）
        // setup: (editor) => {
        //   // 初次化编辑器
        //   editor.on('init', () => {
        //     that.isInit = true //告知是初始化\
        //     if (that.value) {
        //       editor.setContent(that.value)
        //       that.isInit = false
        //     }
        //     editor.on('input change undo redo', () => {
        //       // this.value = editor.getContent()
        //       //此处设置为false很好解决光标前置问题
        //       that.isInit = false
        //     })
        //   })
        // },
      },
      myValue: '',
      isInit: false, //是否初始化
    }
  },
  computed: {
    inputListeners() {
      const newListeners = {
        ...this.$listeners,
        input: (event) => {
          this.$emit('input', event)
        },
      }
      return newListeners
    },
  },
  mounted() {
    tinymce.init({})
  },
  beforeDestroy: function () {
    tinymce.remove(this.tinymceId)
  },
  methods: {
    /**
     * 获取富文本text类型内容
     */
    getTextContent(){
      const editor = tinymce.get(this.tinymceId)
      return editor.getContent({'format' : 'text'})
    },
    setTextContent(value){
      this.myValue = value;
    },
  },
  watch: {
    value(val) {
      //用户vue绑定回显
      if (this.isInit) {
        this.isInit = false
        this.$nextTick(() => {
          const editor = tinymce.get(this.tinymceId)
          editor.setContent(val) 
        })
      }
    },
  }
};
</script>

<style scoped lang="less">
.tinymce-editor{
  width: 100%;
  height: 100%;
  :deep(.tox-tinymce){
    border: 1px solid #e8e8e8;
  }
}
</style>
